package cn.goour.web.dser.controller.user

import cn.goour.web.base.entity.Msg
import cn.goour.web.dser.service.SchoolIpService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.ResponseBody
import javax.servlet.http.HttpServletRequest

@Controller
@RequestMapping("/user/schoolIp")
open class UserSchoolIpController {
    @Autowired
    lateinit var service: SchoolIpService

    @ResponseBody
    @RequestMapping("searchIp", method = arrayOf(RequestMethod.POST), params = arrayOf("building", "room"))
    open fun getByBuildingAndRoom(building: String, room: String, request: HttpServletRequest): Msg {
        val msg = try {
            val re = service.getByBuildingAndRoom(building, room)
            if (re != null) {
                val json = re.toMap()
                json["msg"] = "" + request.servletContext.getAttribute("searchIp")
                Msg(bean = json)
            } else {
                Msg(code = 1, msg = "没有获取到该宿舍IP", bean = mapOf(Pair("msg", "没有获取到该宿舍IP")))
            }
        } catch (e: Exception) {
            logger.error("查询内网IP错误", e)
            Msg(1, "没有获取到该宿舍IP（error）", bean = mapOf(Pair("msg", "没有获取到该宿舍IP（error）")))
        }

        return msg
    }

    companion object {
        private val logger = LoggerFactory.getLogger(UserSchoolIpController::class.java)
    }
}